package org.jeecg.modules.demo.levelset.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.util.TokenUtils;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.demo.levelset.entity.LevelSet;
import org.jeecg.modules.demo.levelset.service.ILevelSetService;
import org.jeecg.modules.demo.membermanagement.entity.MemberManagement;
import org.jeecg.modules.demo.membermanagement.service.IMemberManagementService;
import org.jeecg.modules.util.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;

/**
 * @Description: 会员等级设置
 * @Author: jeecg-boot
 * @Date: 2021-12-31
 * @Version: V1.0
 */
@Api(tags = "会员等级设置")
@RestController
@RequestMapping("/levelset/levelSet")
@Slf4j
public class LevelSetController extends JeecgController<LevelSet, ILevelSetService> {
    @Autowired
    private ILevelSetService levelSetService;
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private IMemberManagementService memberManagementService;

    /**
     * 分页列表查询
     *
     * @param levelSet
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "会员等级设置-分页列表查询")
    @ApiOperation(value = "会员等级设置-分页列表查询", notes = "会员等级设置-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(LevelSet levelSet,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }

        levelSetService.updateMemberNum();
        String rankName = req.getParameter("rankName");
//        QueryWrapper<LevelSet> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("store_id", storeId);
//        QueryGenerator.initQueryWrapper(queryWrapper,levelSet, req.getParameterMap());
        Page<LevelSet> page = new Page<>(pageNo, pageSize);
        IPage<LevelSet> pageList = levelSetService.searchLevelSet(page, rankName, storeId);
        return Result.OK(pageList);
    }

    @GetMapping(value = "/getList")
    public Result<?> queryPageList(HttpServletRequest req) {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }

        List<LevelSet> list = levelSetService.list(new QueryWrapper<LevelSet>().eq("store_id", storeId).orderByAsc("rank_num"));
        if (list == null || list.size() == 0) {
            return Result.error("店铺还未创建会员等级，需要相关人员先创建会员等级");
        }
        return Result.OK(list);
    }

    /**
     * 添加
     *
     * @param levelSet
     * @return
     */
    @AutoLog(value = "会员等级设置-添加")
    @ApiOperation(value = "会员等级设置-添加", notes = "会员等级设置-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody LevelSet levelSet, HttpServletRequest req) {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }
        List<LevelSet> list = levelSetService.list(new QueryWrapper<LevelSet>().eq("store_id", storeId));
        long count = list.stream().filter(ls -> ls.getRankName().equals(levelSet.getRankName())).count();
        if (count > 0) {
            return Result.error("该店铺已有同名会员等级！");
        }
        if (oConvertUtils.isEmpty(levelSet.getRankNum())) {
            return Result.error("请先输入等级序号");
        }
        if (levelSetService.getCountByNum(storeId, levelSet.getRankNum()) > 0) {
            return Result.error("该等级序号已经存在,请修改后重试!");
        }
        if (levelSet.getDiscount() <= 0 || levelSet.getDiscount() > 10) {
            return Result.error("折扣要在0-10范围内（不包含0）");
        }
        levelSet.setStoreId(storeId);
        levelSetService.save(levelSet);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param levelSet
     * @return
     */
    @AutoLog(value = "会员等级设置-编辑")
    @ApiOperation(value = "会员等级设置-编辑", notes = "会员等级设置-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody LevelSet levelSet, HttpServletRequest req) {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }
        List<LevelSet> list = levelSetService.list(new QueryWrapper<LevelSet>()
                .eq("store_id", storeId)
                .ne("id", levelSet.getId()));
        long count = list.stream().filter(ls -> ls.getRankName().equals(levelSet.getRankName())).count();
        if (count > 0) {
            return Result.error("该店铺已有同名会员等级！");
        }
        if (oConvertUtils.isEmpty(levelSet.getRankNum())) {
            return Result.error("请先输入等级序号");
        }
        QueryWrapper<LevelSet> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("store_id", storeId);
        queryWrapper.eq("rank_num", levelSet.getRankNum());
        queryWrapper.ne("id", levelSet.getId());
        List<LevelSet> data = levelSetService.list(queryWrapper);
        if (!data.isEmpty()) {
            return Result.error("该等级序号已经存在,请修改后重试!");
        }
        if (levelSet.getDiscount() <= 0 || levelSet.getDiscount() > 10) {
            return Result.error("折扣要在0-10范围内（不包含0）");
        }
        levelSetService.updateById(levelSet);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "会员等级设置-通过id删除")
    @ApiOperation(value = "会员等级设置-通过id删除", notes = "会员等级设置-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        int count = memberManagementService.count(new QueryWrapper<MemberManagement>().eq("level_id", id));
        if (count > 0) {
            return Result.error("该会员等级下还有关联的会员，请修改会员属性后再删除");
        }
        levelSetService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "会员等级设置-批量删除")
    @ApiOperation(value = "会员等级设置-批量删除", notes = "会员等级设置-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    @Transactional(rollbackFor = Exception.class)
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        List<String> idList = Arrays.asList(ids.split(","));
        int count = memberManagementService.count(new QueryWrapper<MemberManagement>().in("level_id", idList));
        if (count > 0) {
            return Result.error("选择的会员等级中还有关联的会员，请修改会员属性后再删除");
        }
        this.levelSetService.removeByIds(idList);
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "会员等级设置-通过id查询")
    @ApiOperation(value = "会员等级设置-通过id查询", notes = "会员等级设置-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        LevelSet levelSet = levelSetService.getById(id);
        if (levelSet == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(levelSet);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param levelSet
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, LevelSet levelSet) {
        return super.exportXls(request, levelSet, LevelSet.class, "会员等级设置");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, LevelSet.class);
    }

}
